'use strict';

const _ = require('lodash');
const moment = require('moment');


exports.index = async ctx => {
  const { query } = ctx.request;
  let pageSize = 10;
  if (query.pageSize) pageSize = Number(query.pageSize);
  const where = {};
  const { id, userId, status, storeId } = query;
  const currentUser = await ctx.model.User.findByPk(ctx.state.user.sub);
  const store = await ctx.model.Store.findOne({ where: { userId: currentUser.id } });
  if (store) where.storeId = store.id;
  if (id) where.id = id;
  if (userId) where.userId = userId;
  if (storeId) where.storeId = storeId;
  switch (status) {
    case 'useable':
      where.usedAt = null;
      where.expiredDate = {
        [ctx.model.Op.gte]: moment().format('YYYYMMDD'),
      };
      break;
    case 'used':
      where.usedAt = {
        [ctx.model.Op.not]: null,
      };
      break;
    case 'expired':
      where.usedAt = null;
      where.expiredDate = {
        [ctx.model.Op.lte]: moment().format('YYYYMMDD'),
      };
      break;
    default:

  }
  const options = {
    limit: pageSize,
    offset: query.currentPage ? pageSize * (query.currentPage - 1) : 0,
    order: [
      [ 'id', 'DESC' ],
    ],
    raw: true,
    where,
  };
  const {
    count: total, rows: list,
  } = await ctx.model.Coupon.findAndCountAll(options);
  ctx.body = {
    list,
    pagination: {
      total,
      pageSize,
      current: parseInt(query.currentPage, 10) || 1,
    },
  };
};

exports.show = async ctx => {
  const options = { raw: true };
  const coupon = await ctx.model.Coupon.findByPk(ctx.params.id, options);
  if (coupon) {
    ctx.body = coupon;
  } else {
    ctx.status = 404;
  }
};

exports.create = async ctx => {
  ctx.validate({
    amount: { type: 'int' },
    require: { type: 'int' },
    expiredDate: { type: 'date' },
    storeId: { type: 'int', required: false },
  });
  const { expiredDate, amount, require, storeId } = ctx.request.body;
  const time = moment(expiredDate).format('YYYYMMDD');
  const data = { amount, require, expiredDate: time, storeId };
  console.log('await ctx.model.Coupon.create', expiredDate);
  const currentUser = await ctx.model.User.findByPk(ctx.state.user.sub);
  console.log('app controller create currentUser', currentUser);
  const { role } = currentUser;
  const store = await ctx.model.Store.findOne({ where: { userId: currentUser.id } });
  console.log('app controller create store', store);
  if (store && store.userId === currentUser.id) {
    data.storeId = store.id;
    console.log('app controller create data data', data);
    const coupon = await ctx.model.Coupon.create(_.pickBy(
      _.pick(
        data,
        [ 'amount', 'require', 'expiredDate', 'storeId' ]
      ),
      value => value !== null
    ));
    ctx.body = coupon;
  }
  if (role === 'admin') {
    const coupon = await ctx.model.Coupon.create(_.pickBy(
      _.pick(
        data,
        [ 'amount', 'require', 'expiredDate', 'storeId' ]
      ),
      value => value !== null
    ));
    ctx.body = coupon;
  }
};

exports.update = async ctx => {
  const coupon = await ctx.model.Coupon.findByPk(ctx.params.id);
  if (coupon) {
    ctx.validate({
      amount: { type: 'int', required: false },
      require: { type: 'int', required: false },
      expiredDate: { type: 'date', required: false },
    });
    ctx.body = await coupon.update(_.pickBy(
      _.pick(
        ctx.request.body,
        [ 'amount', 'require' ]
      ),
      value => value !== null
    ));
  } else {
    ctx.status = 404;
  }
};

exports.destroy = async ctx => {
  const coupon = await ctx.model.Coupon.findByPk(ctx.params.id);
  if (coupon) {
    await coupon.destroy();
    ctx.status = 204;
  } else {
    ctx.status = 404;
  }
};
